package com.sls.game.service.impl;

import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.util.ServerDateAndTime;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.assist.Helper;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.dao.GoodsOrderDAO;
import com.sls.game.dao.GoodsOrderLogDAO;
import com.sls.game.parser.tencent.ParseTencentConfigFile;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.GoodsOrderLog;
import com.sls.game.pojo.TencentGoodsInfo;
import com.sls.game.service.TencentOrderQueryService;

@Service("tencentOrderQueryService")
public class TencentOrderQueryServiceImpl implements TencentOrderQueryService {

	private static Logger log = Logger
			.getLogger(TencentOrderQueryServiceImpl.class);
	private int ORDER_NOT_EXIST = 130;
	private Gson gson = null;
	@Resource(name = "goodsOrderDAO")
	private GoodsOrderDAO goodsOrderDAO;
	@Resource(name = "goodsOrderLogDAO")
	private GoodsOrderLogDAO goodsOrderLogDAO;

	public TencentOrderQueryServiceImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public String updateQueryOrder(String body, Head head)
			throws ServerDisponseException {
		// 对消息body进行解析
		TencentGoodsInfo parameterInfo = gson.fromJson(body,
				TencentGoodsInfo.class);
		this.validate(parameterInfo);
		this.validateField(parameterInfo);
		
		String address = "";
		TencentGoodsInfo tencentInfo = ParseTencentConfigFile
				.readTencentConfigFile();
		if (tencentInfo != null) {
			address = tencentInfo.getOrderAddress();
			if (StringUtils.isNotEmpty(address)) {
				address = address.trim();
			}
		}
		
		String mch_id = "";
		String enc_key = "";
		String orderId = parameterInfo.getTran_seq();
		GoodsOrderInfo order = this.goodsOrderDAO.queryByOrderId(orderId);
		if (order == null) {
			TencentGoodsInfo respInfo = new TencentGoodsInfo();
			respInfo.setMch_id(mch_id);
			respInfo.setTran_seq(orderId);
			respInfo.setRet(ORDER_NOT_EXIST);
			return gson.toJson(respInfo);
		}else {
			//工号
		    mch_id = order.getRegisterAccount();
		    //获取对应的密钥
			enc_key = getEnc_key(mch_id);
			
		}
		// 签名字符串
		String sign = createSignStr(parameterInfo, mch_id, enc_key);
		// 访问地址
		String url = assembleParameter(parameterInfo, address, mch_id, sign);
		TencentGoodsInfo resInfo = sendHttpRequest(url);
		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		if (resInfo != null) {
			goodsOrderInfo.setOrderId(resInfo.getTran_seq());
			goodsOrderInfo.setSupOrderSuccessTime(resInfo.getTran_date());
			int ret = resInfo.getRet();
			int orderState = resInfo.getOrder_status();
			// 更新订单
			String status = ""; // 0：失败 1：成功 2：处理中 3：存疑 5: 订单不存在
								// 6: 其它
			if (ret == 0) {
				if (orderState == 0) {
					// 初始
				} else if (orderState == 1) {
					// 完成，已扣款，已发货
					status = "1";
				} else if (orderState == 2) {
					// 未扣款，未发货
					status = "0";
				} else if (orderState == 3) {
					// 已扣款，发货不成功，系统会自动补发货
					status = "3";
				} else if (orderState == 4) {
					// 正在交易，已扣款，尚未发货
					status = "2";
				} else if (orderState == 6) {
					// 未扣款，未发货
					status = "0";
				}
				goodsOrderInfo.setStatus(status);
				updateOrderAndLog(resInfo, goodsOrderInfo);
			}
			String result = gson.toJson(resInfo);
			return result;
		}

		return null;
	}

	
	/**
	 * 获取腾讯工号对应的密钥
	 * @param mch_id
	 * 				订单对应的工号
	 * @return
	 */
	private String getEnc_key(String mch_id){
		TencentGoodsInfo tencentInfo = ParseTencentConfigFile
				.readTencentConfigFile();
		String enc_key = "";
		String mch_id_zhejiang = "";
		String enc_key_zhejiang = "";
		if (tencentInfo != null) {
			mch_id_zhejiang = tencentInfo.getMch_id_zhejiang();
			enc_key_zhejiang = tencentInfo.getEnc_key_zhejiang();
			
			if (StringUtils.isNotEmpty(mch_id_zhejiang)) {
				mch_id_zhejiang = mch_id_zhejiang.trim();
			}
			if (StringUtils.isNotEmpty(enc_key_zhejiang)) {
				enc_key_zhejiang = enc_key_zhejiang.trim();
			}
			//获取密钥
			if (mch_id_zhejiang.equals(mch_id)) {
				enc_key = tencentInfo.getEnc_key_zhejiang();
			}
		}
		
		return enc_key;
	}
	
	/**
	 * 更新订单状态
	 * 
	 * @param resInfo
	 * @param goodsOrderInfo
	 */
	private void updateOrderAndLog(TencentGoodsInfo resInfo,
			GoodsOrderInfo goodsOrderInfo) {
		// 数据更新
		try {
			goodsOrderDAO.update(goodsOrderInfo);
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
		String orderNo = resInfo.getTran_seq();
		// 写订单日志
		try {
			GoodsOrderInfo goodsOrderInfo1 = new GoodsOrderInfo();
			goodsOrderInfo1 = this.goodsOrderDAO.queryByOrderId(orderNo);
			if (goodsOrderInfo1 != null) {
				GoodsOrderLog orderLog = Helper.copy(goodsOrderInfo1);
				orderLog.setId(UUID.randomUUID().toString());
				orderLog.setModifyTime(ServerDateAndTime
						.getNowDateTimeOfFormat());
				this.goodsOrderLogDAO.insert(orderLog);
			}
		} catch (Exception e) {
			log.error(e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}
	}

	/**
	 * 发送订单查询请求
	 * 
	 * @param url
	 * @return
	 */
	private TencentGoodsInfo sendHttpRequest(String url) {
		TencentGoodsInfo tencentGoodsInfo = null;
		HttpClient httpClient = new HttpClient();
		try {
			// 供应商返回消息编码方式
			String supplyEncode = "GBK";
			String resultStr = httpClient.doGet(url, supplyEncode);
			tencentGoodsInfo = ParseTencentConfigFile
					.parseOderQueryResponse(resultStr);

		} catch (Exception e) {
			log.error(e);
		}
		return tencentGoodsInfo;
	}

	/**
	 * 拼接参数
	 * 
	 * @param parameterInfo
	 * @param mch_id
	 * @param sign
	 * @param address
	 * @return
	 */
	private String assembleParameter(TencentGoodsInfo parameterInfo,
			String address, String mch_id, String sign) {
		String orderId = parameterInfo.getTran_seq();
		String tranDate = parameterInfo.getTran_date();
		StringBuilder builder = new StringBuilder();
		// http://esales.qq.com/cgi-bin/esales_sell_dir_qry_order_status.cgi?
		// mch_id=xxx&tran_seq=xxx&tran_date=xxx&sign=xxx;
		builder.append(address);
		builder.append("?");
		builder.append("mch_id=");
		builder.append(mch_id);
		builder.append("&");
		builder.append("tran_date=");
		builder.append(tranDate);
		builder.append("&");
		builder.append("tran_seq=");
		builder.append(orderId);
		builder.append("&");
		builder.append("sign=");
		builder.append(sign);
		String parameter = builder.toString();
		return parameter;
	}

	/**
	 * 生成签名字符串
	 * 
	 * @param parameterInfo
	 * @param mch_id
	 * @param enc_key
	 * @return
	 */
	private String createSignStr(TencentGoodsInfo parameterInfo, String mch_id,
			String enc_key) {
		String orderId = parameterInfo.getTran_seq();
		String tranDate = parameterInfo.getTran_date();
		// mch_id=xxx&tran_seq=xxx&tran_date=xxx||enc_key
		StringBuilder sb = new StringBuilder();
		sb.append("mch_id=");
		sb.append(mch_id);
		sb.append("&");
		sb.append("tran_date=");
		sb.append(tranDate);
		sb.append("&");
		sb.append("tran_seq=");
		sb.append(orderId);
		sb.append("||");
		sb.append(enc_key);
		String data = sb.toString();
		String signStr = UtilMD5Encryption.createMD5Encryption(data);
		if (StringUtils.isEmpty(signStr)) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SIGN_ERROR.getCode(),
					ExceptionCodeDes.SIGN_ERROR.getDescription());
		}
		return signStr;
	}

	private void validate(TencentGoodsInfo tencentInfo)
			throws ServerDisponseException {
		if (tencentInfo == null) {
			throw new ServerDisponseException(
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getCode(),
					ExceptionCodeDes.PARSE_REQUEST_ERROR.getDescription());
		}
	}

	private void validateField(TencentGoodsInfo tencentInfo) {
		if (StringUtils.isEmpty(tencentInfo.getTran_seq())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.SLS_ORDERNO_NULL.getCode(),
					ExceptionCodeDes.SLS_ORDERNO_NULL.getDescription());
		} else if (StringUtils.isEmpty(tencentInfo.getTran_date())) {
			throw new ServerDisponseException(
					ExceptionCodeDes.EN_LINK_TIME_EMPTY.getCode(),
					ExceptionCodeDes.EN_LINK_TIME_EMPTY.getDescription());
		}
	}
}
